package com.woniu.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.user.infra.model.City;
import com.woniu.user.infra.mapper.CityMapper;
import com.woniu.user.service.CityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.service.dto.CityDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 城市表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-26
 */
@Service
public class CityServiceImpl extends ServiceImpl<CityMapper, City> implements CityService {
    @Resource
    private StringRedisTemplate srt;
    private ObjectMapper om = new ObjectMapper();

    private List<CityDto> listCity() {
        List<City> types = list();
        //JAVA代码构建树形结构
        //用来做返回的根节点集合
        List<CityDto> cd = new ArrayList<>();
        //构建一个包含所有节点Dto对象的集合
        List<CityDto> allTypes = new ArrayList<>();
        //构建map集合存放所有节点
        Map<Integer, CityDto> maps = new HashMap<>();
        for (City type : types) {
            CityDto cityDto = BeanUtil.copyProperties(type, CityDto.class);
            if (cityDto.getParentId() <= 0) cd.add(cityDto);
            allTypes.add(cityDto);
            maps.put(cityDto.getCityId(), cityDto);
        }
        //通过儿子找父亲的方式构建树形结构
        for (CityDto type : allTypes) {
            CityDto parent = maps.get(type.getParentId());
            if(parent==null) continue;
            if (parent.getChildren()==null) parent.setChildren(new ArrayList<>());
            parent.getChildren().add(type);
        }
        return cd;
    }
    @Override
    public List<CityDto> findType() throws JsonProcessingException {
        //redis查询
        String cityType = srt.opsForValue().get("lxlg:city");
        List<CityDto> cd = null;
        if (cityType == null || cityType.trim().equals("")) {
            cd=listCity();
            //存入redis
            srt.opsForValue().set("lxlg:city",om.writeValueAsString(cd));
            srt.expire("lxlg:city",1, TimeUnit.SECONDS);
        }else {
            cd=om.readValue(cityType, new TypeReference<List<CityDto>>() {
            });
        }
        return cd;
    }
}
